package com.xr.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xr.blog.pojo.BlogArticle;
import com.xr.blog.pojo.BlogArticleTag;
import com.xr.blog.pojo.BlogComment;
import com.xr.blog.pojo.BlogTag;
import com.xr.blog.service.BlogArticleService;
import com.xr.blog.service.BlogArticleTagService;
import com.xr.blog.service.BlogCommentService;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.ValidatorUtils;
import com.xr.blog.tools.constant.Code;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 文章表
 *
 * @author XRJ
 * @email 1033835209@qq.com
 * @date 2020-07-07 20:31:38
 */
@RestController
@RequestMapping("/squirrelblog")
public class BlogArticleController {
    @Autowired
    BlogArticleService blogArticleService;

    @Autowired
    BlogArticleTagService blogArticleTagService;

    @Autowired
    BlogCommentService blogCommentService;

    /**
     * 查询最新的文章
     * @param number 需要查询的条数
     * @return
     */
    @GetMapping(value = "/article/latest",produces = "application/json;charset=UTF-8")
    public Result<List<BlogArticle>> latest(Integer number){
        List<BlogArticle> articleList=blogArticleService.findLatestArticle(number);
        return Result.of(Code.SC_OK.getState(),"查询成功",articleList);
    }


    @GetMapping(value = "/article/getList",produces = "application/json;charset=UTF-8")
    public Result<IPage<BlogArticle>> list(@RequestParam(value = "current",required = false,defaultValue = "1") Integer currentPage,
                       @RequestParam(value = "size",required = false,defaultValue = "10") Integer pageSize,
                       @RequestParam(value = "title",required = false) String title,
                       @RequestParam(value = "categoryId",required = false) Long categoryId,
                       @RequestParam(value = "status",required = false) Integer status,
                       @RequestParam(value = "type",required = false) Integer type){
        Page page=new Page(currentPage,pageSize);
        IPage<BlogArticle> ipage=blogArticleService.findArticleByCondition(page,title,categoryId,status,type);
        return Result.of(Code.SC_OK.getState(),"查询成功",ipage);
    }

    /**
     * 修改部分参数时使用，如状态、是否置顶、是否开启评论等。
     * @param article 封装参数的文章实体
     * @return
     */
    @PostMapping(value = "/article/modify",produces = "application/json;charset=UTF-8")
    public Result<BlogArticle> modify(@RequestBody @Validated(Update.class) BlogArticle article){
        article.setUpdateTime(new Date());
        boolean res=blogArticleService.updateById(article);
        return res?Result.of(Code.SC_OK.getState(),"修改成功",article):Result.of(Code.MUNEINSERTTOID_EOOR.getState(),"修改失败",null);
    }

    /**
     * 根据id批量删除。
     * @param ids id数组
     * @return
     */
    @DeleteMapping(value = "/article/batchDelete",produces = "application/json;charset=UTF-8")
    public Result remove(Long[] ids){
        List<Long> idList= Stream.of(ids).collect(Collectors.toList());
        blogCommentService.deleteByArticleIds(idList);
        blogArticleTagService.remove(new QueryWrapper<BlogArticleTag>().in(!idList.isEmpty(),"article_id", idList));
        return blogArticleService.removeByIds(Arrays.asList(ids))?Result.of(Code.SC_OK.getState(),"删除成功",null):Result.of(Code.DEL_FAIL.getState(),"删除失败",null);
    }


    /**
     * 发布文章。
     * @param article 文章内容实体
     * @return
     */
    @PostMapping(value = "/article/publish",produces = "application/json;charset=UTF-8")
    public Result save(@RequestBody @Validated(Insert.class) BlogArticle article){
//        ValidatorUtils.validate(article);
        if(StringUtils.isBlank(article.getUrl())){
            article.setUrl(article.getTitle());
        }
        article.setUpdateTime(new Date());
        boolean res=blogArticleService.saveOrUpdate(article);
        if(!res){
            return Result.of(Code.MUNEINSERTTOID_EOOR.getState(),"保存失败",null);
        }
        if(!CollectionUtils.isEmpty(article.getTags())){
            Long articleId=article.getId()!=null?article.getId():blogArticleService.findArticleByUrl(article.getUrl()).getId();
            List<Long> tagIds=article.getTags().stream().map(BlogTag::getId).collect(Collectors.toList());
            res=blogArticleTagService.saveBatch(articleId,tagIds);
            if(!res){
                return Result.of(Code.MUNEINSERTTOID_EOOR.getState(),"文章已成功保存，但关联标签保存失败",null);
            }
        }
        return Result.of(Code.SC_OK.getState(),"保存成功",article);
    }



}
